package com.hyl.service;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;

import java.util.Arrays;

/**
 * @Description 用于嵌入到指定的某一个方法中
 * @Author com.com.hyl
 * @Date 2022/9/24 9:32
 **/
public class BaseService {

	//前置：方法执行之前
	public void before(JoinPoint joinPoint){
		System.out.println("前置。。");
		System.out.println("调用："+joinPoint.getTarget()
				+"，方法："+joinPoint.getSignature()+",参数："
				+ Arrays.toString(joinPoint.getArgs()));
	}

	//后置：方法执行之后【没有异常的情况】
	public void afterReturn(JoinPoint joinPoint,
	                        Object ret){ //方法执行完成之后，获取返回值
		System.out.println("后置。。");
		System.out.println("调用："+joinPoint.getTarget()
				+"，方法："+joinPoint.getSignature()+",参数："
				+ Arrays.toString(joinPoint.getArgs())
				+"，返回结果："+ret);

	}

	//异常：方法出错
	public void doException(JoinPoint joinPoint,
	                        RuntimeException e){ //方法在运行过程中，出现错误
		System.out.println("异常。。");
		System.out.println("调用："+joinPoint.getTarget()
				+"，方法："+joinPoint.getSignature()+",参数："
				+ Arrays.toString(joinPoint.getArgs())
				+"，异常："+e);

	}

	//最终：无论方法是否出错，都会执行
	public void after(JoinPoint joinPoint){
		System.out.println("最终。。");
		System.out.println("调用："+joinPoint.getTarget()
				+"，方法："+joinPoint.getSignature()+",参数："
				+ Arrays.toString(joinPoint.getArgs())
				);
	}


	public void arround(ProceedingJoinPoint joinPoint){
		System.out.println("前置。。");
		System.out.println("调用："+joinPoint.getTarget()
				+"，方法："+joinPoint.getSignature()+",参数："
				+ Arrays.toString(joinPoint.getArgs()));
		try{

			//调用需要执行的方法
			Object ret = joinPoint.proceed();

			System.out.println("后置。。");
			System.out.println("调用："+joinPoint.getTarget()
					+"，方法："+joinPoint.getSignature()+",参数："
					+ Arrays.toString(joinPoint.getArgs())
					+"，返回结果："+ret);
		} catch (Throwable throwable) {
			System.out.println("异常。。");
			System.out.println("调用："+joinPoint.getTarget()
					+"，方法："+joinPoint.getSignature()+",参数："
					+ Arrays.toString(joinPoint.getArgs())
					+"，异常："+throwable);
		} finally {
			System.out.println("最终。。");
			System.out.println("调用："+joinPoint.getTarget()
					+"，方法："+joinPoint.getSignature()+",参数："
					+ Arrays.toString(joinPoint.getArgs())
			);
		}
	}




}
